# coding=utf-8
import requests


class TieBaSpider(object):
    """tieba spider"""
    def __init__(self, tieba_name):
        self.tieba_name = tieba_name
        self.headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"}
        self.url_temp = "https://tieba.baidu.com/f?kw=" + tieba_name + "&ie=utf-8&pn={}"

    def get_url_list(self):
        return [self.url_temp.format(i*50) for i in range(1000)]

    def parse_url(self, url):
        response = requests.get(url, headers=self.headers)
        return response.content.decode()

    def save_response_data(self, resp, page_num):
        file_path = "{}_第{}页.html".format(self.tieba_name, page_num)
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(resp)

    def run(self):
        # 准备URL列表
        url_list = self.get_url_list()
        # 发送请求
        for url in url_list:
            resp = self.parse_url(url)

            # 保存
            page_num = url_list.index(url) + 1
            self.save_response_data(resp, page_num)


if __name__ == '__main__':
    s = TieBaSpider("李毅")
    s.run()
